package net.zhengxinyun.unifyApp.Util;

import com.mchange.util.AssertException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

public class WordUtil  {

   // private static Configuration configuration = null;

   // public static final  String template = WordUtil.class.getClassLoader().getResource("/").getPath();
   //private static final  String  template = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/wordMould/";
  // private static  String path ="/static/wordMould/";




    private WordUtil()
    {
        throw new AssertException();
    }


    public static File createDoc(Map<?,?> dataMap ,String ftlName) {
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(WordUtil.class,"/static/wordMould/");
        String name =ftlName;
        File f = new File(name);
        Template temp =  null;

        Writer write =null;
        try {

            temp=configuration.getTemplate(ftlName,"UTF-8");
           // System.out.println("开始");
           // System.out.println(temp);

            write  = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
            temp.process(dataMap,write);
            write.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  f;
    }

    public static void exportWrodFile(HttpServletResponse response, Map map,String ftlName,String fiName) throws IOException {
        System.out.println("kaishi");

        File file  = null;

        InputStream fileInp = null;
        ServletOutputStream out  = null;


        try {
            file  = createDoc(map,ftlName);


            fileInp = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");

            String fileName = fiName;

            response.setHeader("Content-Disposition","attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName,"UTF-8")))  );

            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int b = -1;
            while ((b= fileInp.read(buffer)) !=-1)
            {
                out.write(buffer,0,b);
            }
        } finally {

            if(fileInp != null) fileInp.close();
            if(out != null) out.close();
            if(file != null) file.delete(); // 删除临时文件

        }






    }


}
